package user

import (
	v1 "gitee.com/sweetsunnyflower/carpooling-server-go/app/http/controllers/api/v1"
	"gitee.com/sweetsunnyflower/carpooling-server-go/app/models/driver"
	"gitee.com/sweetsunnyflower/carpooling-server-go/app/policies"
	"gitee.com/sweetsunnyflower/carpooling-server-go/app/requests"
	"github.com/gofiber/fiber/v2"
	"github.com/spf13/cast"
)

type DriversController struct {
	v1.BaseController
}

func (controller *DriversController) Index(c *fiber.Ctx) error {
	drivers := driver.All()
	return controller.Json(c, drivers)
}

func (controller *DriversController) Show(c *fiber.Ctx) error {
	driverModel := driver.Get(cast.ToUint64(c.Query("id")))
	if driverModel.ID == 0 {
		return controller.NotFound(c)
	}
	return controller.Json(c, driverModel)
}

func (controller *DriversController) Store(c *fiber.Ctx) error {

	request := new(requests.DriverRequest)

	if errors := requests.ValidateDriver(c, request); len(errors) > 0 {
		return controller.ValidationError(c, errors)
	}

	if driver.GetByUserId(controller.Auth(c)).ID > 0 {
		return controller.Faield(c, "司机信息已经存在，无需再次添加")
	}

	driverModel := driver.Driver{
		UserId:                cast.ToUint64(controller.Auth(c)),
		Year:                  request.Year,
		LicenseNumber:         request.LicenseNumber,
		LicenseType:           request.LicenseType,
		DriverNumber:          request.DriverNumber,
		IdCard:                request.IdCard,
		LicenseExpirationDate: controller.ToTime(request.LicenseExpirationDate),
		EmergencyContactName:  request.EmergencyContactName,
		EmergencyContactPhone: request.EmergencyContactPhone,
	}
	driverModel.Create()
	if driverModel.ID > 0 {
		return controller.Json(c, driverModel)
	} else {
		return controller.Faield(c, "创建失败")
	}
}

func (controller *DriversController) Update(c *fiber.Ctx) error {

	driverModel := driver.Get(cast.ToUint64(c.Query("id")))
	if driverModel.ID == 0 {
		return controller.NotFound(c)
	}

	userId := controller.Auth(c)
	if ok := policies.CanModifyDriver(userId, driverModel); !ok {
		return controller.Forbidden(c)
	}

	request := new(requests.DriverRequest)

	if errors := requests.ValidateDriver(c, request); len(errors) > 0 {
		return controller.ValidationError(c, errors)
	}

	// driverModel.FieldName = request.FieldName
	rowsAffected := driverModel.Save()
	if rowsAffected > 0 {
		return controller.Success(c)
	} else {
		return controller.Faield(c, "更新失败")
	}
}

func (controller *DriversController) Delete(c *fiber.Ctx) error {

	driverModel := driver.Get(cast.ToUint64(c.Query("id")))
	if driverModel.ID == 0 {
		return controller.NotFound(c)
	}

	userId := controller.Auth(c)

	if ok := policies.CanModifyDriver(userId, driverModel); !ok {
		return controller.Forbidden(c)
	}

	rowsAffected := driverModel.Delete()
	if rowsAffected > 0 {
		return controller.Success(c)
	}

	return controller.Faield(c, "删除失败")
}
